import UIKit

/// 用户数据模型
struct UserData: Codable {
  let companyId: Int?
  let headImgUrl: String
  let openId: String
  let phone: String
  let token: String?
  let unionId: String
  let userId: Int?
  let userName: String?
}

class LoginViewController: UIViewController {

  // MARK: - UI Components
  private let closeButton: UIButton = {
    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setImage(UIImage(systemName: "xmark"), for: .normal)
    button.tintColor = .black
    return button
  }()

  private let titleLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "账号密码登录"
    label.font = .systemFont(ofSize: 24, weight: .medium)
    return label
  }()

  private let accountTextField: UITextField = {
    let textField = UITextField()
    textField.translatesAutoresizingMaskIntoConstraints = false
    textField.placeholder = "请输入账号"
    textField.borderStyle = .roundedRect
    //        textField.text = "wjj"
    textField.clearButtonMode = .whileEditing
    return textField
  }()

  private let passwordTextField: UITextField = {
    let textField = UITextField()
    textField.translatesAutoresizingMaskIntoConstraints = false
    textField.placeholder = "请输入密码"
    textField.borderStyle = .roundedRect
    textField.isSecureTextEntry = true
    //        textField.text = "wjj123654"
    textField.clearButtonMode = .whileEditing
    return textField
  }()

  private let errorLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.textColor = .red
    label.font = .systemFont(ofSize: 12)
    label.isHidden = true
    return label
  }()

  private lazy var loginButton: UIButton = {
    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("登录", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.backgroundColor = UIColor(red: 255 / 255, green: 99 / 255, blue: 31 / 255, alpha: 1)
    button.layer.cornerRadius = 22
    button.addTarget(self, action: #selector(loginTapped), for: .touchUpInside)
    return button
  }()

  // MARK: - Lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()
    setupUI()
    setupActions()
  }

  // MARK: - UI Setup
  private func setupUI() {
    view.backgroundColor = .white

    view.addSubview(closeButton)
    view.addSubview(titleLabel)
    view.addSubview(accountTextField)
    view.addSubview(passwordTextField)
    view.addSubview(errorLabel)
    view.addSubview(loginButton)

    NSLayoutConstraint.activate([
      closeButton.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
      closeButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
      closeButton.widthAnchor.constraint(equalToConstant: 44),
      closeButton.heightAnchor.constraint(equalToConstant: 44),

      titleLabel.topAnchor.constraint(equalTo: closeButton.bottomAnchor, constant: 20),
      titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),

      accountTextField.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 40),
      accountTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
      accountTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
      accountTextField.heightAnchor.constraint(equalToConstant: 44),

      passwordTextField.topAnchor.constraint(equalTo: accountTextField.bottomAnchor, constant: 20),
      passwordTextField.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
      passwordTextField.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
      passwordTextField.heightAnchor.constraint(equalToConstant: 44),

      errorLabel.topAnchor.constraint(equalTo: passwordTextField.bottomAnchor, constant: 8),
      errorLabel.leadingAnchor.constraint(equalTo: passwordTextField.leadingAnchor),

      loginButton.topAnchor.constraint(equalTo: errorLabel.bottomAnchor, constant: 30),
      loginButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
      loginButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
      loginButton.heightAnchor.constraint(equalToConstant: 44),
    ])
  }

  private func setupActions() {
    closeButton.addTarget(self, action: #selector(closeTapped), for: .touchUpInside)
  }

  // MARK: - Actions
  @objc private func closeTapped() {
    dismiss(animated: true)
  }

  @objc private func loginTapped() {
    guard let account = accountTextField.text, !account.isEmpty,
      let password = passwordTextField.text, !password.isEmpty
    else {
      showError("请输入账号和密码")
      return
    }

    // 显示加载状态
    loginButton.isEnabled = false
    loginButton.setTitle("登录中...", for: .normal)

    MobClick.event("login", label: "iOS")

    // 准备登录参数
    let loginBody: [String: Any] = [
      "username": account,
      "password": password,
      "deviceType": "iOS",
    ]

    HttpClient.shared.postWithAutoHUD(endpoint: "/testLogin", body: loginBody) {
      [weak self] (userData: UserData?) in
      guard let userData = userData, let self = self else {
        return
      }
      // 🎉 登录成功，保存 Token
      if let token = userData.token, let userName = userData.userName {
        UserDefaults.baodan.set(token, forKey: UserDefaults.tokenKey)
        UserDefaults.baodan.set(userName, forKey: UserDefaults.userNameKey)
        UserDefaults.baoDan.saveUserDataToUserDefaults(userData: userData)

        print("✅ 登录成功，用户名：\(userName)")
        // 友盟
        if let userId = userData.userId {
          MobClick.profileSignIn(withPUID: "\(userId)")
        }
        if let userName = userData.userName {
          MobClick.userProfile("userName", to: userName)
        }
        MobClick.userProfileMobile(userData.phone)

        if let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate
          as? SceneDelegate
        {
          let window = sceneDelegate.window

          let mainTabBarController = MainTabBarController()

          // 切换根视图控制器
          UIView.transition(
            with: window!, duration: 0.5, options: .transitionCrossDissolve,
            animations: {
              window?.rootViewController = mainTabBarController  // 登录成功后，切换到主页面
            })
        }
      } else {
        self.showError("登录失败：未获取到用户信息")
      }
    }

    HttpClient.shared.post(endpoint: "/testLogin", body: loginBody) {
      [weak self] (result: Result<UserData, NetworkError>) in
      DispatchQueue.main.async {
        self?.loginButton.isEnabled = true
        self?.loginButton.setTitle("登录", for: .normal)

        switch result {
        case .success(let userData):
          // 🎉 登录成功，保存 Token
          if let token = userData.token, let userName = userData.userName {
            UserDefaults.baodan.set(token, forKey: UserDefaults.tokenKey)
            UserDefaults.baodan.set(userName, forKey: UserDefaults.userNameKey)
            UserDefaults.baoDan.saveUserDataToUserDefaults(userData: userData)

            print("✅ 登录成功，用户名：\(userName)")

            if let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate
              as? SceneDelegate
            {
              let window = sceneDelegate.window

              let mainTabBarController = MainTabBarController()

              // 切换根视图控制器
              UIView.transition(
                with: window!, duration: 0.5, options: .transitionCrossDissolve,
                animations: {
                  window?.rootViewController = mainTabBarController  // 登录成功后，切换到主页面
                })
            }
          } else {
            self?.showError("登录失败：未获取到用户信息")
          }

        case .failure(let error):
          // ❌ 处理错误
          switch error {
          case .serverError(let code):
            self?.showError("服务器错误: \(code)")
          case .noData:
            self?.showError("未收到服务器响应")
          case .decodingError:
            self?.showError("数据解析错误")
          case .invalidURL:
            self?.showError("无效的URL")
          case .customError(let message):
            self?.showError(message)
          }
        }
      }
    }
  }

  private func showError(_ message: String) {
    errorLabel.text = message
    errorLabel.isHidden = false
  }
}
